package com.twotwoshop.service.order.listener;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.twotwoshop.commom.order.OrderStatus;
import com.twotwoshop.commom.rabbitmq.RabbitConstants;
import com.twotwoshop.domin.common.dtos.ResponseResult;
import com.twotwoshop.domin.goods.dtos.ProductDto;
import com.twotwoshop.domin.order.pojo.Order;
import com.twotwoshop.domin.order.pojo.OrderDetail;
import com.twotwoshop.fegin.api.goods.IGoodsClient;
import com.twotwoshop.service.order.mapper.OrderDetailMapper;
import com.twotwoshop.service.order.mapper.OrderMapper;
import com.twotwoshop.service.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
@Component
@RequiredArgsConstructor
public class OrderListener {



    private final OrderMapper orderMapper;

    private final OrderService orderService;

    private final OrderDetailMapper orderDetailMapper;

    private final IGoodsClient goodsClient;


    /**
     * 延迟队列 监听新订单过期时间
     *
     * @param
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitConstants.TWOTWO_DLX_ORDER_TOPIC, durable = "true"),//开启持久化
            exchange = @Exchange(name = RabbitConstants.TWOTWO_DLX_ORDER_EXCHANGE, type = ExchangeTypes.DIRECT, delayed = "true"),//设置为死信交换机
            key = "delay"
    ))
    @Transactional
    public void onMessage(Order order) {

        //如果获取成功
        if (order != null) {

            //延迟队列验证用户支付状态 若未支付 恢复库存
            payStatus(order);

        } else {

            return;
        }

    }

    //验证用户是否支付
    private void payStatus(Order order) {

        //1.获取支付状态
        Order order3 = orderMapper.selectById(order.getId());

        if (order3 == null) {
            throw new RuntimeException("订单未创建");
        }

        //2.如果用户已支付
        if (order3.getStatus() == OrderStatus.PAID_NOT_SHIPPED) {
            log.info("延迟队列检测到用户已支付");
            return;
        }

        //2.如果用户未支付 取消订单 回滚库存
        if (order3.getStatus() == OrderStatus.UNPAID) {

            orderService.cancelOrder(order.getId());

            log.error("用户未支付 库存回滚成功");

            }

        }



    }



